<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="110px"
    >
      <el-form-item label="茶民宿名字" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入茶民宿名字"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="茶民宿标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入茶民宿标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['tea:homestay:add']"
          >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['tea:homestay:edit']"
          >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tea:homestay:remove']"
          >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['tea:homestay:export']"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Download"
          :disabled="multiple"
          @click="handleExportCode"
          v-hasPermi="['tea:homestay:export']"
          >导出二维码
        </el-button>
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="homestayList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!--      <el-table-column label="茶民宿主键" align="center" prop="id"/>-->
      <el-table-column label="茶民宿名字" align="center" prop="name" />
      <el-table-column
        label="茶民宿封面"
        align="center"
        prop="cover"
        width="100"
      >
        <template #default="scope">
          <image-preview :src="scope.row.cover" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column
        label="轮播图"
        align="center"
        prop="imgArray"
        width="100"
      >
        <template #default="scope">
          <image-preview
            v-for="item in scope.row.imgArray"
            :key="item"
            :src="item"
            :width="50"
            :height="50"
          />
        </template>
      </el-table-column>
      <el-table-column label="茶民宿标题" align="center" prop="title" />
      <el-table-column
        label="茶民宿详情"
        align="center"
        prop="content"
        width="120"
      >
        <template #default="scope">
          <!-- <span v-html="scope.row.content"></span> -->
          <el-button @click="openDetail(scope.$index)">查看详情</el-button>
        </template>
      </el-table-column>
      <el-table-column label="茶民宿收费" align="center" prop="price" />
      <!-- <el-table-column label="活动时间" align="center" prop="date" width="260">
        <template #default="scope">
          <el-date-picker
              v-if="scope.row.date"
              clearable
              v-model="scope.row.date"
              type="daterange"
              value-format="YYYY-MM-DD"
              readonly
              style="width: 230px"
          >
          </el-date-picker>
        </template>
      </el-table-column>
      <el-table-column label="服务标签" align="center" prop="tagArray">
        <template #default="scope">
          <el-tag v-for="tag in scope.row.tagArray" :key="tag" type="info">{{ tag }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="民宿地址" align="center" prop="address" />
      <el-table-column label="联系电话" align="center" prop="phone" />
      <el-table-column label="排序" align="center" prop="orderNum" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Share"
            @click="handleShare(scope.row, scope.$index)"
            >分享
          </el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['tea:homestay:edit']"
            >修改
          </el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tea:homestay:remove']"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改茶民宿管理对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="600px"
      append-to-body
      :zIndex="100"
    >
      <el-form
        ref="homestayRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="茶民宿名字" prop="name">
          <el-input v-model="form.name" placeholder="请输入茶民宿名字" />
        </el-form-item>
        <el-form-item label="茶民宿封面" prop="cover">
          <image-upload v-model="form.cover" :limit="1" />
        </el-form-item>
        <el-form-item label="轮播图" prop="imgArray">
          <image-upload v-model="form.imgArray" />
        </el-form-item>
        <el-form-item label="茶民宿标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入茶民宿标题" />
        </el-form-item>
        <el-form-item label="茶民宿详情">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="茶民宿收费" prop="price">
          <el-input v-model="form.price" placeholder="请输入茶民宿收费" />
        </el-form-item>
        <!-- <el-form-item label="活动时间" prop="date">
          <el-date-picker clearable
                          v-model="form.date"
                          type="date"
                          value-format="YYYY-MM-DD"
                          placeholder="请选择活动时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="服务标签" prop="tagArray">
          <el-select
              v-model="form.tagArray"
              multiple
              filterable
              allow-create
              default-first-option
              :reserve-keyword="false"
              placeholder="请选择服务标签"
              style="width: 240px"
          >
            <el-option v-for="item in form.tagArray" :key="item" :label="item" :value="item"/>
          </el-select>
        </el-form-item> -->
        <el-form-item label="民宿地址">
          <el-input
            v-model="form.address"
            placeholder="请输入民宿地址"
            :min-height="192"
          />
        </el-form-item>
        <el-form-item label="联系电话">
          <el-input
            type="tel"
            placeholder="请输入联系电话"
            v-model="form.phone"
            :min-height="192"
          />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number
            v-model="form.orderNum"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="茶民宿图文详情" width="500px" v-model="detail">
      <div v-html="homestayList[nowIndex].content"></div>
    </el-dialog>
    <el-dialog title="二维码" width="250px" align-center v-model="code">
      <div style="display: flex; flex-direction: column">
        <img :src="codeContent" alt="二维码" style="" />
        <div style="text-align: center">
          {{ homestayList[nowIndex]?.name || homestayList[nowIndex]?.title }}
        </div>
      </div>
      <div style="display: flex; justify-content: center; padding: 10px 0">
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="
            downloadCode(
              codeContent,
              homestayList[nowIndex]?.name || homestayList[nowIndex]?.title
            )
          "
          >下载
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="Homestay">
  import {
    listHomestay,
    getHomestay,
    delHomestay,
    addHomestay,
    updateHomestay
  } from '@/api/tea/homestay'
  import QRCode from 'qrcode'

  const { proxy } = getCurrentInstance()

  const homestayList = ref([])
  const open = ref(false)
  const code = ref(false)
  const codeContent = ref('')
  const nowIndex = ref(0)
  const detail = ref(false)
  const loading = ref(true)
  const showSearch = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const total = ref(0)
  const title = ref('')

  const data = reactive({
    form: {},
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      name: null,
      title: null
    },
    rules: {
      name: [
        { required: true, message: '茶民宿名字不能为空', trigger: 'blur' }
      ],
      title: [
        { required: true, message: '茶民宿标题不能为空', trigger: 'blur' }
      ],
      orderNum: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
    }
  })

  const { queryParams, form, rules } = toRefs(data)

  /** 查询茶民宿管理列表 */
  function getList() {
    loading.value = true
    listHomestay(queryParams.value).then(response => {
      homestayList.value = response.rows
      total.value = response.total
      loading.value = false
      homestayList.value.forEach(item => {
        if (item.tagArray != '' && item.tagArray != null)
          item.tagArray = item.tagArray.split(',')
        if (item.date != '' && item.date != null)
          item.date = item.date.split(',')
        if (item.imgArray != '' && item.imgArray != null)
          item.imgArray = item.imgArray.split(',')
      })
    })
  }

  // 取消按钮
  function cancel() {
    open.value = false
    reset()
  }

  // 表单重置
  function reset() {
    form.value = {
      id: null,
      name: null,
      cover: null,
      imgArray: null,
      title: null,
      content: null,
      price: null,
      date: null,
      tagArray: null,
      address: null,
      phone: null,
      orderNum: 0
    }
    proxy.resetForm('homestayRef')
  }

  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
  }

  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm('queryRef')
    handleQuery()
  }

  // 多选框选中数据
  function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
  }

  /** 新增按钮操作 */
  function handleAdd() {
    reset()
    open.value = true
    title.value = '添加茶民宿管理'
  }

  /** 修改按钮操作 */
  function handleUpdate(row) {
    reset()
    const _id = row.id || ids.value
    getHomestay(_id).then(response => {
      form.value = {
        ...response.data
      }
      if (form.value.tagArray != '' && form.value.tagArray != null)
        form.value.tagArray = form.value.tagArray.split(',')
      if (form.value.date != '' && form.value.date != null)
        form.value.date = form.value.date.split(',')
      if (form.value.imgArray != '' && form.value.imgArray != null)
        form.value.imgArray = form.value.imgArray.split(',')
      open.value = true
      title.value = '修改茶民宿管理'
    })
  }

  /** 提交按钮 */
  function submitForm() {
    proxy.$refs['homestayRef'].validate(valid => {
      if (valid) {
        let post = {
          ...form.value
        }
        if (post.imgArray != null) {
          post.imgArray = Array(post.imgArray).join(',')
        }
        if (post.tagArray != null) {
          post.tagArray = Array(post.tagArray).join(',')
        }
        if (post.date != null) {
          post.date = post.date.join(',')
        }
        if (post.id != null) {
          updateHomestay(post).then(response => {
            proxy.$modal.msgSuccess('修改成功')
            open.value = false
            getList()
          })
        } else {
          addHomestay(post).then(response => {
            proxy.$modal.msgSuccess('新增成功')
            open.value = false
            getList()
          })
        }
      }
    })
  }

  /** 删除按钮操作 */
  function handleDelete(row) {
    const _ids = row.id || ids.value
    proxy.$modal
      .confirm('是否确认删除茶民宿管理编号为"' + _ids + '"的数据项？')
      .then(function () {
        return delHomestay(_ids)
      })
      .then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
      })
      .catch(() => {})
  }

  /** 导出按钮操作 */
  function handleExport() {
    proxy.download(
      'tea/homestay/export',
      {
        ...queryParams.value
      },
      `homestay_${new Date().getTime()}.xlsx`
    )
  }

  /** 打开详情 */
  function openDetail(index) {
    nowIndex.value = index
    detail.value = true
  }

  function handleShare(row, index) {
    let text = `${import.meta.env.VITE_DOMAIN_NAME}/homestay/${
      row.id
    }?type=share`
    QRCode.toDataURL(text, (err, url) => {
      nowIndex.value = index
      codeContent.value = url
      code.value = true
    })
  }

  function downloadCode(url, name) {
    const image = new Image()
    image.src = url
    // 创建canvas元素
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    image.onload = () => {
      // 设置canvas大小
      canvas.width = image.width
      canvas.height = image.height + 30
      // 绘制背景色
      ctx.fillStyle = 'white' // 背景颜色
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      // 绘制图片
      ctx.drawImage(image, 0, 0, image.width, image.height)
      // 设置文字样式
      ctx.font = '16px Arial'
      ctx.fillStyle = 'black' // 文字颜色
      ctx.textAlign = 'center' // 文字居中
      // 绘制文字
      ctx.fillText(name, canvas.width / 2, image.height + 10)
      // 将canvas转换为Base64编码
      const dataURL = canvas.toDataURL('image/png')
      // 创建一个链接元素
      const link = document.createElement('a')
      link.href = dataURL
      link.download = `${name}.png` // 设置下载的文件名
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }

  function handleExportCode() {
    const _ids = ids.value
    for (let i = 0; i < _ids.length; i++) {
      let text = `${import.meta.env.VITE_DOMAIN_NAME}/homestay/${
        _ids[i]
      }?type=share`
      QRCode.toDataURL(text, (err, url) => {
        const name =
          homestayList.value.find(item => item.id === _ids[i])?.name ||
          homestayList.value.find(item => item.id === _ids[i])?.title
        downloadCode(url, name)
      })
    }
  }
  getList()
</script>
